<?php
namespace app\controller;

use app\Controller;
use Endroid\QrCode\QrCode;
use app\service\Alipay as Pay;
use app\model\mall\Order;
use Alipay\EasySDK\Kernel\Factory;
use Alipay\EasySDK\Kernel\Util\ResponseChecker;
use Alipay\EasySDK\Kernel\Config;
use think\facade\App;

/*
 * 支付宝控制器
 * @author Mateng <Index.php>
 */
class Alipay extends Controller
{
    // 通知
    public function notify() {
        // 实例支付对象
        $pay = new Pay(config('alipay.'));
        $result = $pay->notify();
        if($result){
            $order = $this->orderInfo($result['out_trade_no']);
            if($order->pay_state !== 2){
                $order->save(['pay_at' => time(), 'pay_state' => 2, 'pay_type' => 2, 'transaction_id' => $result['transaction_id']], true);
                ob_clean();
                echo $pay->getNotifySuccessReply();
            }
        }
    }
    /*
     * 支付宝地址二跳
     */
    public function jump()
    {
        $orderNo = input('get.out_trade_no');
        $type = substr($orderNo, 0, 2);
        if(!in_array($type, ['CA', 'PR', 'RI'])){
            return json(['msg' => '该订单不存在', 'code' => 0]);
        }
        switch($type){
            case 'CA':
                $path = 'card/checkout?no=' . $orderNo;
                break;
            case 'RI':
                $order = OrderRights::with('code')->where('id', $orderNo)->findOrFail();
                $path = 'privilege/charge?id=' . $order->code->rights_id . '&no=' . $orderNo;
                break;
            default:
                $path = 'order/checkout?no=' . $orderNo;
                break;
        }

        return redirect('https://lc.51lulu.com/pages/' . $path . '&wxback=true');
    }
    /*
     * 查询支付页面
     * @return string
     * @throws \WeChat\Exceptions\InvalidResponseException
     */
    public function query()
    {
        $pay = new Pay;
        $result = $pay->queryOrder(input('get.orderNo'));
        if($result) {
            return json($result);
        }
        return json(['code' => '$2', 'msg' => '$1']);
    }
    // 退款
    public function refund($out_trade_no, $refund_fee) {
        // 实例支付对象
        $pay = new Pay(config('alipay.'));
        // 参考链接：https://docs.open.alipay.com/api_1/alipay.trade.refund
        return $pay->refund($out_trade_no, $refund_fee);
    }
    /**
     * 小程序绑定
     * 
     * @return array
     */
    public function bind()
    {
        $post = $this->request->post();
        $model = Model::wehre('mobile', $post['account'])->findOrEmpty();
        $model->save($post);
        // 获取token
        $data = ['access_token' => Ident::token(['id' => $model->id, 'idcard' => $model->idcard]), 'id' => $model->id]; //参数为用户认证的信息，请自行添加
        redis()->hset('AccessTokenList', $data['access_token'], $data + ['login_at' => time()]);
        return json($data);
    }
    /**
     * 密码登录.
     * 
     */
    public function login()
    {
        $post = $this->request->post();
        $model = Model::where('mobile', $post['account'])->findOrEmpty();

        if (!$model->isEmpty() && $model->status !== 2) {
            return ['code' => 0, 'msg' => '账号异常!'];
        }

        $model->save(['status' => 2] + $post);

        $wechat = UserThird::where([['user_id', '=', $model->id], ['type', '=', 3]])->findOrEmpty();
        $wechat->save(['user_id' => $model->id, 'openid' => $post['openid'], 'type' => 3]);

        $data = ['token' => Ident::token(['uid' => $model->id, 'account' => $model->mobile, 'openid' => $post['openid']]), 'id' => $model->id]; //参数为用户认证的信息，请自行添加
        redis()->hset('AccessTokenList', $data['token'], $data + ['openid' => $model->openid, 'mobile' => $model->mobile, 'login_at' => time()]);

        return json($data + [
            'is_auth' => !empty($model->mobile),
            'nickname' => $post['nickname'] ?? '',
            'avatar' => $post['avatar'] ?? '',
        ]);
    }
}
